<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
      <BasicForm @register="registerForm" @eventFormModel="eventFormModel" />
      <VerifyInfo ref="childRef" :verifyType="2"/>
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import dayjs from 'dayjs'
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import VerifyInfo from './verifyInfo.vue'
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../MonsterHrProjectSetup.data';
    import {saveOrUpdate} from '../MonsterHrProjectSetup.api';
    import { USER_INFO_KEY } from '/@/enums/cacheEnum'
    import { getAuthCache } from '/@/utils/auth'
    import { dateMonths } from '@/utils/tool'
    let user:any = getAuthCache(USER_INFO_KEY) || {}
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const childRef = ref()
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate, updateSchema}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        if (data.record) {
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
        }
        if(unref(isUpdate)) {
            childRef.value.childMethod(data.record)
        }else {
            childRef.value.childMethod()
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            let f = values.uploadFile ? JSON.parse(values.uploadFile) : []
            
            console.log('f', f)
            let file:any = []
            f.forEach((url) => {
                file.push({
                    annexName: url.fileName,
                    annexType: url.fileType,
                    url: url.filePath,
                })
            })
            values.uploadFile = JSON.stringify(file)
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(Object.assign(values,{annex:JSON.stringify(file)}), isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
    let oTime
    function eventFormModel (e) {
        console.log('表单返回值-totalCost',e.uploadFile)
        let cycle = dateMonths(e.startTime,e.endTime)
        if(cycle && e.endTime) {
            setFieldsValue({ cycle })
        }
        if(oTime != e.startTime) {
            setFieldsValue({ endTime: '' })
        }

        if(e && e.startTime) {
            oTime = e.startTime
            updateSchema({ field: 'endTime', componentProps: { disabledDate: disabledDate }})
        }

        function disabledDate(current) {
            console.log(current.endOf("day"),'current.endOf("day")')
            return current && current < dayjs(e.startTime).subtract(0, 'days').endOf('day')//currentTime < endTime;//禁用小于开始时间的日期
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>